<?php

namespace app\admin\controller;

use think\Db;
use think\Facade\Cache;
use app\admin\model\Dq;

class Area extends Admin
{
    /**
     * 地区显示
     * @return mixed
     */
    public function index()
    {
        $data = model('Dq')->select();
        $this->assign('dq', $data);
        return $this->fetch();
    }

    /**
     * 新增地区
     * @return mixed
     */
    public function add()
    {
        $city = Db::name('Dq')->where(['fid' =>0])->select();//父级城市
        $this->assign('city',$city);
        return $this->fetch();
    }

    /**
     * 编辑地区
     * @return mixed
     */
    public function edit()
    {
        input('id') ? $id = input('id') : $this->error('缺少参数');
        $city = Db::name('Dq')->where(['fid' =>0])->select();//父级城市
        $this->assign('city',$city);
        $info = Db::name('Dq')->where(['id' => $id])->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     *添加地区
     */
    public function addrun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/area/index'));
        } else {
            $area = new Dq();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 0;
            $result = $area->validate(true)->save($data);
            if (false === $result) {
                // 验证失败 输出错误信息
                $this->error($area->getError());
            } else {
                $this->success('地区添加成功', url('admin/area/index'));
            }
        }
    }

    /**
     *编辑地区
     */
    public function editrun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/area/index'));
        } else {
            $area = new Dq();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 0;
            $result = $area->allowField(true)->validate(true)->isUpdate(true)->save($data);
            if ($result !== false) {
                $this->success('地区修改成功', url('admin/area/index'));
            } else {
                // 验证失败 输出错误信息
                $this->error($area->getError());
            }
        }
    }
    //删除菜单
    public function del()
    {
        $id = $this->request->param('id', 0);
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        if (Dq::destroy($id)) {
            $this->success('删除成功');
        } else {
           $this->error('删除失败');
        }
    }
}
